﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DCCMS.Common.Config;
using System.Web.Security;

namespace DCCMS.Web.Admin
{
    public partial class Login : System.Web.UI.Page
    {
        protected override void OnInit(EventArgs e)
        {
            //HttpCookie userCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            //if (userCookie != null)
            //{
            //    this.ctrLogin.UserNameLabelText = HttpContext.Current.User.Identity.Name;
            //}
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                this.projectName.InnerText = GlobalConfig.ProjectName;
                CheckLoginStatus();
            } 
        }
        protected void CheckLoginStatus()
        {

        }

        protected void LoginButton_Click(object sender,EventArgs e)
        {
            //HttpUtility.UrlDecode
            if (FormsAuthentication.Authenticate("Admin", "admin888"))
            {
                FormsAuthentication.SetAuthCookie("Admin", false);
                bool remeber = this.ctrLogin.RememberMeSet;
                FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket("Admin",remeber, 30);
                if (remeber)
                {
                    string HashTicket = FormsAuthentication.Encrypt(Ticket); //加密序列化验证票为字符串
                    HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);
                    UserCookie.Expires = Ticket.Expiration;
                    //生成Cookie
                    HttpContext.Current.Response.Cookies.Add(UserCookie); //输出Cookie
                }
                else if(Request.Cookies[FormsAuthentication.FormsCookieName] != null)
                {
                    HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddDays(-1);
                    HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
                }
                //HttpContext.Current.Response.Redirect(this.GetRedirectUrl()); // 重定向到用户申请的初始页面
                FormsAuthentication.RedirectFromLoginPage("Admin", remeber);
            }
            else
                Response.Write("用户名或者密码错误");
        }
        protected string GetRedirectUrl()
        {
            HttpContext context = HttpContext.Current;
            string returnUrl = context.Request.QueryString["ReturnUrl"];
            if (returnUrl == null)
            {
                return this.ctrLogin.DestinationPageUrl;
            }
            return HttpUtility.UrlDecode(returnUrl);
        }
    }
}